<template>
  <div class="opening-guidance-report">
    <el-card class="report-card">
      <template #header>
        <div class="card-header">
          <span class="card-title">校区开业辅导统计</span>
          <el-button-group class="header-actions">
            <el-button size="mini" icon="el-icon-refresh" @click="refreshData" :loading="loading">刷新</el-button>
            <el-button size="mini" icon="el-icon-download" @click="exportData">导出</el-button>
          </el-button-group>
        </div>
      </template>

      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="8" animated />
      </div>

      <div v-else>
        <!-- 开业统计 -->
        <div class="statistics-section">
          <h3 class="section-title">开业统计</h3>
          <el-row :gutter="20">
            <el-col :span="8">
              <div class="stat-card">
                <div class="stat-header">
                  <span class="stat-title">总开业数</span>
                  <el-tag type="info" size="mini">累计</el-tag>
                </div>
                <div class="stat-value">{{ openingStatistics.totalOpeningCount || 0 }}</div>
                <div class="stat-trend">
                  <span class="trend-text">较上期</span>
                  <span class="trend-value" :class="getTrendClass(openingTrend)">{{ openingTrend > 0 ? '+' : '' }}{{ openingTrend }}%</span>
                </div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="stat-card">
                <div class="stat-header">
                  <span class="stat-title">本月开业数</span>
                  <el-tag type="success" size="mini">本月</el-tag>
                </div>
                <div class="stat-value">{{ openingStatistics.monthlyOpeningCount || 0 }}</div>
                <div class="stat-trend">
                  <span class="trend-text">本月新增</span>
                  <span class="trend-value">{{ openingStatistics.monthlyOpeningCount || 0 }}个</span>
                </div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="stat-card">
                <div class="stat-header">
                  <span class="stat-title">平均开业数</span>
                  <el-tag type="warning" size="mini">月均</el-tag>
                </div>
                <div class="stat-value">{{ openingStatistics.averageOpeningCount || 0 }}</div>
                <div class="stat-trend">
                  <span class="trend-text">每月平均</span>
                  <span class="trend-value">{{ openingStatistics.averageOpeningCount || 0 }}个</span>
                </div>
              </div>
            </el-col>
          </el-row>
        </div>

        <!-- 达标统计 -->
        <div class="statistics-section">
          <h3 class="section-title">达标统计</h3>
          <el-row :gutter="20">
            <el-col :span="8">
              <div class="stat-card">
                <div class="stat-header">
                  <span class="stat-title">总达标数</span>
                  <el-tag type="success" size="mini">达标</el-tag>
                </div>
                <div class="stat-value">{{ qualifiedStatistics.qualifiedCount || 0 }}</div>
                <div class="stat-trend">
                  <span class="trend-text">达标率</span>
                  <span class="trend-value">{{ qualifiedStatistics.qualifiedRate || 0 }}%</span>
                </div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="stat-card">
                <div class="stat-header">
                  <span class="stat-title">达标率</span>
                  <el-tag :type="getQualifiedRateTagType(qualifiedStatistics.qualifiedRate)" size="mini">合格率</el-tag>
                </div>
                <div class="stat-value">{{ qualifiedStatistics.qualifiedRate || 0 }}%</div>
                <el-progress :percentage="qualifiedStatistics.qualifiedRate || 0" :color="getProgressColor(qualifiedStatistics.qualifiedRate)" :stroke-width="6" :show-text="false"></el-progress>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="stat-card">
                <div class="stat-header">
                  <span class="stat-title">平均运营评分</span>
                  <el-tag type="info" size="mini">评分</el-tag>
                </div>
                <div class="stat-value">{{ qualifiedStatistics.averageScore || 0 }}</div>
                <el-rate :model-value="qualifiedStatistics.averageScore / 20 || 0" disabled show-score score-template="{value}分"></el-rate>
              </div>
            </el-col>
          </el-row>
        </div>

        <!-- 区域分布和品牌分布 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="statistics-section">
              <h3 class="section-title">区域分布</h3>
              <div class="chart-container">
                <div v-if="regionalDistribution && regionalDistribution.length" ref="regionChart" style="height: 300px;"></div>
                <el-empty v-else description="暂无区域分布数据" />
              </div>
              <div class="region-stats">
                <div class="region-item" v-for="item in regionalDistribution" :key="item.regionCode">
                  <div class="region-label">
                    <span class="region-name">{{ item.regionName }}</span>
                    <span class="region-count">{{ item.openingCount }}个</span>
                  </div>
                  <el-progress :percentage="item.qualifiedRate" :color="getRegionProgressColor(item.qualifiedRate)" :stroke-width="4"></el-progress>
                </div>
              </div>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="statistics-section">
              <h3 class="section-title">品牌分布</h3>
              <div class="chart-container">
                <div v-if="brandDistribution && brandDistribution.length" ref="brandChart" style="height: 300px;"></div>
                <el-empty v-else description="暂无品牌分布数据" />
              </div>
              <div class="brand-stats">
                <div class="brand-item" v-for="item in brandDistribution" :key="item.brand">
                  <div class="brand-label">
                    <span class="brand-name">{{ item.brand }}</span>
                    <span class="brand-count">{{ item.openingCount }}个</span>
                  </div>
                  <el-progress :percentage="item.qualifiedRate" :color="getBrandProgressColor(item.qualifiedRate)" :stroke-width="4"></el-progress>
                </div>
              </div>
            </div>
          </el-col>
        </el-row>

        <!-- 时间趋势分析 -->
        <div class="statistics-section">
          <h3 class="section-title">时间趋势分析</h3>
          <div class="chart-container">
            <div v-if="timeTrendAnalysis && timeTrendAnalysis.length" ref="trendChart" style="height: 400px;"></div>
            <el-empty v-else description="暂无趋势数据" />
          </div>
        </div>

        <!-- 回访统计 -->
        <div class="statistics-section">
          <h3 class="section-title">回访统计</h3>
          <el-row :gutter="20">
            <el-col :span="8">
              <div class="stat-card">
                <div class="stat-header">
                  <span class="stat-title">回访完成率</span>
                  <el-tag type="success" size="mini">完成</el-tag>
                </div>
                <div class="stat-value">{{ followUpStatistics.completionRate || 0 }}%</div>
                <el-progress :percentage="followUpStatistics.completionRate || 0" :color="getProgressColor(followUpStatistics.completionRate)" :stroke-width="6" :show-text="false"></el-progress>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="stat-card">
                <div class="stat-header">
                  <span class="stat-title">满意度评分</span>
                  <el-tag type="warning" size="mini">评分</el-tag>
                </div>
                <div class="stat-value">{{ followUpStatistics.averageSatisfactionScore || 0 }}</div>
                <el-rate :model-value="followUpStatistics.averageSatisfactionScore || 0" disabled show-score score-template="{value}分"></el-rate>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="stat-card">
                <div class="stat-header">
                  <span class="stat-title">回访总数</span>
                  <el-tag type="info" size="mini">总计</el-tag>
                </div>
                <div class="stat-value">{{ followUpStatistics.totalFollowUpCount || 0 }}</div>
                <div class="stat-trend">
                  <span class="trend-text">已完成</span>
                  <span class="trend-value">{{ followUpStatistics.completedFollowUpCount || 0 }}个</span>
                </div>
              </div>
            </el-col>
          </el-row>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { getGuidanceStatisticsUnified } from '@/api/report/services'

export default {
  name: 'OpeningGuidanceReport',
  props: {
    queryForm: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      loading: false,

      // 开业统计数据
      openingStatistics: {
        totalOpeningCount: 0,
        monthlyOpeningCount: 0,
        averageOpeningCount: 0
      },
      openingTrend: 0,

      // 达标统计数据
      qualifiedStatistics: {
        qualifiedCount: 0,
        qualifiedRate: 0,
        averageScore: 0
      },

      // 区域分布数据
      regionalDistribution: [],

      // 品牌分布数据
      brandDistribution: [],

      // 时间趋势数据
      timeTrendAnalysis: [],

      // 回访统计数据
      followUpStatistics: {
        totalFollowUpCount: 0,
        completedFollowUpCount: 0,
        completionRate: 0,
        averageSatisfactionScore: 0
      },

      // 图表实例
      regionChart: null,
      brandChart: null,
      trendChart: null
    }
  },
  mounted() {
    this.loadData()
    // 监听窗口大小变化，防抖触发展示更新
    this._onResize = this.debounce(() => {
      if (this.regionChart) this.regionChart.resize()
      if (this.brandChart) this.brandChart.resize()
      if (this.trendChart) this.trendChart.resize()
    }, 200)
    window.addEventListener('resize', this._onResize)
  },
  watch: {
    queryForm: {
      handler() {
        this.reloadData()
      },
      deep: true
    }
  },
  beforeDestroy() {
    /**
     * 组件销毁前清理函数
     * 释放 ECharts 实例，避免内存泄漏。
     */
    if (this.regionChart) {
      this.regionChart.dispose()
      this.regionChart = null
    }
    if (this.brandChart) {
      this.brandChart.dispose()
      this.brandChart = null
    }
    if (this.trendChart) {
      this.trendChart.dispose()
      this.trendChart = null
    }
    if (this._onResize) {
      window.removeEventListener('resize', this._onResize)
      this._onResize = null
    }
  },
  methods: {
    /**
     * 防抖包装器
     * 说明：用于包装高频触发的图表初始化与窗口resize事件，避免重复渲染影响性能。
     */
    debounce(fn, wait = 200) {
      let timer = null
      return (...args) => {
        clearTimeout(timer)
        timer = setTimeout(() => fn.apply(this, args), wait)
      }
    },
    /**
     * 重新加载数据
     * 用途：当筛选条件变化时刷新统计与图表。
     */
    reloadData() {
      this.loadData()
    },

    /**
     * 构造后端查询参数（兼容父组件 queryForm 字段）
     * 输入：queryForm 包含 startDate、endDate、regionId、brandId、campusId
     * 输出：后端接口参数（camelCase）：startDate、endDate、managementArea、brand、campusId
     */
    getQueryParams() {
      const params = {}
      if (this.queryForm.startDate) {
        params.startDate = this.queryForm.startDate
      }
      if (this.queryForm.endDate) {
        params.endDate = this.queryForm.endDate
      }
      if (this.queryForm.regionId) {
        params.managementArea = this.queryForm.regionId
      }
      if (this.queryForm.brandId) {
        params.brand = this.queryForm.brandId
      }
      if (this.queryForm.campusId) {
        params.campusId = this.queryForm.campusId
      }
      return params
    },

    /**
     * 刷新数据（手动触发）
     */
    async refreshData() {
      this.$message.success('数据刷新中...')
      await this.loadData()
      this.$message.success('数据已刷新')
    },

    /**
     * 加载综合统计数据并初始化图表
     * 流程：
     * 1) 调用开业辅导统计接口获取月度与总量数据
     * 2) 计算开业统计（总/本月/月均/环比）
     * 3) 计算达标统计（达标数/达标率/平均分）
     * 4) 生成时间趋势（月度开业/达标）
     * 5) 结合服务统计补充区域分布（可选）
     * 6) 映射品牌分布与回访统计
     */
    async loadData() {
      this.loading = true
      this.$emit('loading', true)
      try {
        const params = this.getQueryParams()
        const guidanceResp = await getGuidanceStatisticsUnified(params)

        if (guidanceResp && (guidanceResp.code === 200 || guidanceResp.success || guidanceResp.data)) {
          const payload = guidanceResp.data || guidanceResp

          // 1) 时间趋势与基础总量（兼容旧字段 + 后端 BranchService 的 statistics 字段）
          let monthly = []
          if (Array.isArray(payload.monthlyStatistics)) {
            monthly = payload.monthlyStatistics
          } else if (Array.isArray(payload.timeTrendAnalysis)) {
            monthly = payload.timeTrendAnalysis.map(m => ({
              month: m.month,
              openingCount: Number(m.openingCount || 0),
              qualifiedCount: Number(m.qualifiedCount || 0),
              managementAreaName: m.managementAreaName || m.managementArea || '未知'
            }))
          } else if (Array.isArray(payload.statistics)) {
            // 兼容 BranchService 返回的 statistics（month, managementAreaName, campusCount, qualifiedCount）
            monthly = payload.statistics.map(s => ({
              month: s.month,
              openingCount: Number(s.campusCount || 0),
              qualifiedCount: Number(s.qualifiedCount || 0),
              managementAreaName: s.managementAreaName || s.managementArea || '未知'
            }))
          }

          // 兼容旧构建环境，避免使用可选链操作符
          let totalOpeningCount = Number(
            (payload.totalOpeningCount != null ? payload.totalOpeningCount : (
              payload.openingStatistics && payload.openingStatistics.totalOpeningCount != null
                ? payload.openingStatistics.totalOpeningCount
                : 0
            ))
          )
          let totalQualifiedCount = Number(
            (payload.totalQualifiedCount != null ? payload.totalQualifiedCount : (
              payload.qualifiedStatistics && payload.qualifiedStatistics.qualifiedCount != null
                ? payload.qualifiedStatistics.qualifiedCount
                : 0
            ))
          )
          // 如果未返回总量，则根据 statistics 汇总
          if ((!totalOpeningCount || !totalQualifiedCount) && Array.isArray(payload.statistics)) {
            totalOpeningCount = payload.statistics.reduce((sum, s) => sum + Number(s.campusCount || 0), 0)
            totalQualifiedCount = payload.statistics.reduce((sum, s) => sum + Number(s.qualifiedCount || 0), 0)
          }

          // 2) 开业统计
          const now = new Date()
          const currentMonthKey = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`
          const monthlyOpeningCount = monthly.filter(m => String(m.month) === currentMonthKey).reduce((sum, m) => sum + Number(m.openingCount || 0), 0)
          const monthlyGroups = monthly.map(m => Number(m.openingCount || 0))
          const averageOpeningCount = monthlyGroups.length > 0 ? Math.round(monthlyGroups.reduce((a, b) => a + b, 0) / monthlyGroups.length) : 0
          this.openingStatistics = {
            totalOpeningCount,
            monthlyOpeningCount,
            averageOpeningCount
          }

          // 环比趋势（最近两月）
          if (monthlyGroups.length >= 2) {
            const last = monthlyGroups[monthlyGroups.length - 1]
            const prev = monthlyGroups[monthlyGroups.length - 2]
            this.openingTrend = prev === 0 ? (last > 0 ? 100 : 0) : Math.round(((last - prev) / prev) * 100)
          } else {
            this.openingTrend = 0
          }

          // 3) 达标统计
          const qualifiedRate = totalOpeningCount > 0 ? Math.round((totalQualifiedCount / totalOpeningCount) * 100) : 0
          this.qualifiedStatistics = {
            qualifiedCount: totalQualifiedCount,
            qualifiedRate,
            averageScore: Number(
              (payload.averageOperationScore != null ? payload.averageOperationScore : (
                payload.qualifiedStatistics && payload.qualifiedStatistics.averageScore != null
                  ? payload.qualifiedStatistics.averageScore
                  : 0
              ))
            )
          }

          // 4) 时间趋势分析（补齐最近12个月缺失项）
          const rawTrend = monthly.map(m => ({
            month: m.month,
            openingCount: Number(m.openingCount || 0),
            qualifiedCount: Number(m.qualifiedCount || 0)
          }))
          const filledTrend = this.fillLast12Months(rawTrend)
          this.timeTrendAnalysis = filledTrend

          // 5) 区域分布（guidance 月度聚合）
          const regionAgg = {}
          monthly.forEach(m => {
            const key = m.managementAreaName || m.managementArea || '未知'
            if (!regionAgg[key]) {
              regionAgg[key] = { openingCount: 0, qualifiedCount: 0 }
            }
            regionAgg[key].openingCount += Number(m.openingCount || 0)
            regionAgg[key].qualifiedCount += Number(m.qualifiedCount || 0)
          })
          this.regionalDistribution = Object.keys(regionAgg).map(name => {
            const open = regionAgg[name].openingCount
            const qual = regionAgg[name].qualifiedCount
            const rate = open > 0 ? Math.round((qual / open) * 100) : 0
            return { regionCode: name, regionName: name, openingCount: open, qualifiedCount: qual, qualifiedRate: rate }
          })

          // 优先使用后端统一接口提供的区域分布
          if (Array.isArray(payload.regionalDistribution) && payload.regionalDistribution.length) {
            this.regionalDistribution = payload.regionalDistribution
          }

          // 6) 品牌分布与回访统计
          this.brandDistribution = Array.isArray(payload.brandDistribution) ? payload.brandDistribution : []
          const fu = payload.followUpStatistics || {}
          this.followUpStatistics = {
            totalFollowUpCount: Number(fu.totalFollowUpCount || 0),
            completedFollowUpCount: Number(fu.completedFollowUpCount || 0),
            completionRate: Number(fu.completionRate || 0),
            averageSatisfactionScore: Number(fu.averageSatisfactionScore || 0)
          }

          // 初始化图表
          this.$nextTick(() => {
            this.initCharts()
          })
        } else {
          const msg = guidanceResp && guidanceResp.msg ? guidanceResp.msg : '接口返回异常'
          this.$message.error('获取数据失败: ' + msg)
        }
      } catch (error) {
        console.error('加载数据失败:', error)
        this.$message.error('加载数据失败，请稍后重试')
      } finally {
        this.loading = false
        this.$emit('loading', false)
      }
    },

    /**
     * 补足最近12个月趋势数据
     * 输入：[{ month: 'yyyy-MM', openingCount, qualifiedCount }]
     * 逻辑：以当前月为终点，前推11个月，若缺失则补0；按月份升序返回
     */
    fillLast12Months(trendList) {
      const now = new Date()
      const months = []
      for (let i = 11; i >= 0; i--) {
        const d = new Date(now.getFullYear(), now.getMonth() - i, 1)
        const key = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`
        months.push(key)
      }
      const map = {}
      trendList.forEach(item => {
        map[String(item.month)] = {
          openingCount: Number(item.openingCount || 0),
          qualifiedCount: Number(item.qualifiedCount || 0)
        }
      })
      return months.map(m => ({
        month: m,
        openingCount: map[m] ? map[m].openingCount : 0,
        qualifiedCount: map[m] ? map[m].qualifiedCount : 0
      }))
    },

    /**
     * 获取趋势样式类名
     * 输入：趋势百分比数值
     * 输出：样式类（上升/下降/持平）
     */
    getTrendClass(trend) {
      if (trend > 0) return 'trend-up'
      if (trend < 0) return 'trend-down'
      return 'trend-flat'
    },

    /**
     * 根据达标率返回标签类型
     * 说明：>=90 success；>=70 warning；否则 danger
     */
    getQualifiedRateTagType(rate) {
      if (rate >= 90) return 'success'
      if (rate >= 70) return 'warning'
      return 'danger'
    },

    /**
     * 获取通用进度条颜色
     */
    getProgressColor(percentage) {
      if (percentage >= 90) return '#67c23a'
      if (percentage >= 70) return '#e6a23c'
      return '#f56c6c'
    },

    /**
     * 获取区域达标率颜色
     */
    getRegionProgressColor(rate) {
      if (rate >= 90) return '#67c23a'
      if (rate >= 70) return '#e6a23c'
      return '#f56c6c'
    },

    /**
     * 获取品牌达标率颜色
     */
    getBrandProgressColor(rate) {
      if (rate >= 90) return '#67c23a'
      if (rate >= 70) return '#e6a23c'
      return '#f56c6c'
    },

    /**
     * 初始化所有图表
     */
    initCharts() {
      const run = this.debounce(() => {
        this.initRegionChart()
        this.initBrandChart()
        this.initTrendChart()
      }, 200)
      run()
    },

    /**
     * 初始化区域分布图表（饼图）
     */
    initRegionChart() {
      const chartDom = this.$refs.regionChart
      if (!chartDom || !this.regionalDistribution.length) return

      if (this.regionChart) {
        this.regionChart.dispose()
      }
      this.regionChart = echarts.init(chartDom)

      const option = {
        title: { text: '区域开业分布', left: 'center', textStyle: { fontSize: 14, fontWeight: 'normal' } },
        tooltip: { trigger: 'item', formatter: '{b}: {c}个 ({d}%)' },
        legend: { orient: 'vertical', left: 'left', top: 'center' },
        series: [
          {
            name: '开业数',
            type: 'pie',
            radius: ['40%', '70%'],
            center: ['60%', '50%'],
            data: this.regionalDistribution.map(item => ({ name: item.regionName, value: item.openingCount })),
            emphasis: { itemStyle: { shadowBlur: 10, shadowOffsetX: 0, shadowColor: 'rgba(0,0,0,0.5)' } },
            label: { formatter: '{b}\n{c}个' }
          }
        ],
        color: ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272']
      }
      this.regionChart.setOption(option)
    },

    /**
     * 初始化品牌分布图表（柱状图）
     */
    initBrandChart() {
      const chartDom = this.$refs.brandChart
      if (!chartDom || !this.brandDistribution.length) return

      if (this.brandChart) {
        this.brandChart.dispose()
      }
      this.brandChart = echarts.init(chartDom)

      const option = {
        title: { text: '品牌开业分布', left: 'center', textStyle: { fontSize: 14, fontWeight: 'normal' } },
        tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' }, formatter: '{b}: {c}个' },
        grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
        xAxis: { type: 'category', data: this.brandDistribution.map(item => item.brand), axisLabel: { interval: 0, rotate: 30 } },
        yAxis: { type: 'value', name: '开业数' },
        series: [{ name: '开业数', type: 'bar', data: this.brandDistribution.map(item => item.openingCount), itemStyle: { color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{ offset: 0, color: '#83bff6' }, { offset: 0.5, color: '#188df0' }, { offset: 1, color: '#188df0' }]) }, label: { show: true, position: 'top' } }]
      }
      this.brandChart.setOption(option)
    },

    /**
     * 初始化时间趋势图表（折线图）
     */
    initTrendChart() {
      const chartDom = this.$refs.trendChart
      if (!chartDom || !this.timeTrendAnalysis.length) return

      if (this.trendChart) {
        this.trendChart.dispose()
      }
      this.trendChart = echarts.init(chartDom)

      const months = this.timeTrendAnalysis.map(item => item.month)
      const openingCounts = this.timeTrendAnalysis.map(item => item.openingCount)
      const qualifiedCounts = this.timeTrendAnalysis.map(item => item.qualifiedCount)

      const option = {
        title: { text: '月度开业趋势', left: 'center', textStyle: { fontSize: 14, fontWeight: 'normal' } },
        tooltip: { trigger: 'axis', axisPointer: { type: 'cross', label: { backgroundColor: '#6a7985' } } },
        legend: { data: ['开业数', '达标数'], top: 30 },
        grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
        xAxis: { type: 'category', boundaryGap: false, data: months },
        yAxis: { type: 'value', name: '数量' },
        series: [{ name: '开业数', type: 'line', smooth: true, data: openingCounts, areaStyle: { opacity: 0.3 }, itemStyle: { color: '#5470c6' } }, { name: '达标数', type: 'line', smooth: true, data: qualifiedCounts, areaStyle: { opacity: 0.3 }, itemStyle: { color: '#91cc75' } }]
      }
      this.trendChart.setOption(option)
    },

    /**
     * 获取导出数据（含查询条件与北京时间导出时间）
     */
    getExportData() {
      const exportTime = new Intl.DateTimeFormat('zh-CN', { timeZone: 'Asia/Shanghai', dateStyle: 'short', timeStyle: 'medium' }).format(new Date())
      return {
        openingStatistics: this.openingStatistics,
        qualifiedStatistics: this.qualifiedStatistics,
        regionalDistribution: this.regionalDistribution,
        brandDistribution: this.brandDistribution,
        timeTrendAnalysis: this.timeTrendAnalysis,
        followUpStatistics: this.followUpStatistics,
        exportTime,
        query: this.getQueryParams()
      }
    },

    /**
     * 导出数据事件（交给父组件统一处理导出）
     */
    exportData() {
      this.$message.success('正在准备导出数据...')
      this.$emit('export', { type: 'opening_guidance', data: this.getExportData() })
    }
  }
}
</script>

<style lang="scss" scoped>
.opening-guidance-report {
  padding: 20px;
}

.report-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.loading-container {
  padding: 40px 20px;
}

.statistics-section {
  margin-bottom: 30px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 2px solid #409eff;
}

.stat-card {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  text-align: center;
  transition: transform 0.3s ease;

  &:hover {
    transform: translateY(-2px);
  }
}

.stat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.stat-title {
  font-size: 14px;
  color: #909399;
  font-weight: 500;
}
.stat-value {
  font-size: 32px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 10px;
}
.stat-trend {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: #909399;
}
.trend-text {
  margin-right: 10px;
}
.trend-value {
  font-weight: bold;
}
.trend-up {
  color: #67c23a;
}
.trend-down {
  color: #f56c6c;
}
.trend-flat {
  color: #909399;
}

.chart-container {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.region-stats,
.brand-stats {
  background: white;
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.region-item,
.brand-item {
  margin-bottom: 15px;
  &:last-child {
    margin-bottom: 0;
  }
}

.region-label,
.brand-label {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  font-size: 14px;
}

.region-name,
.brand-name {
  font-weight: 500;
  color: #303133;
}

.region-count,
.brand-count {
  color: #409eff;
  font-weight: bold;
}

@media (max-width: 768px) {
  .opening-guidance-report {
    padding: 10px;
  }
  .statistics-section {
    padding: 15px;
  }
  .stat-value {
    font-size: 24px;
  }
  .chart-container {
    padding: 15px;
  }
}
</style>
